﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;

namespace xmlTranslate
{
    public class BaiduTranslate : ITranslate
    {
        public string Translate(string sourceStr, bool saveSource)
        {
            string strURL = "http://fanyi.baidu.com/v2transapi" + string.Format("?from={0}&to={1}&query={2}", "en", "zh", HttpUtility.UrlEncode(sourceStr));
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strURL);
            request.Host = "fanyi.baidu.com";
            request.Referer = "http://fanyi.baidu.com/";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream stream = response.GetResponseStream();
            //获取响应内容  
            string text = null;
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                text = reader.ReadToEnd();
            }
            try
            {
                JavaScriptSerializer js = new JavaScriptSerializer();
                jieguo jg = js.Deserialize<jieguo>(text);
                var targetText = jg.trans_result.data[0].dst.ToString();
                if (saveSource)
                    return $"{targetText}({sourceStr})";
                else
                    return targetText;
            }
            catch
            {
                return sourceStr;
            }
        }
    }


    class jieguo
    {
        public trans_result trans_result;
    }

    class trans_result
    {
        public List<data> data;
    }
    //{"from":"en","to":"zh","domain":"all","type":2,"status":0,"data":[{"dst":"你好","src":"hello","relation":[],"result":[[0,"你好",["0|5"],[],["0|5"],["0|6"]]]}],"phonetic":[{"src_str":"你","trg_str":"nǐ"},{"src_str":"好","trg_str":"hǎo"}]}
    class data
    {
        public string dst;
        public string src;
    }
}
